from app.aoduo_admin.models import AdminAccount
from django.http import JsonResponse
from django.contrib.auth.hashers import check_password
from django.utils.timezone import now
from rest_framework.views import APIView
from common.authCheck.adminAuth import check_admin_login, getAdminUser
import json


class AdminBaseInfoView(APIView):

    def get(self, request):
        """
        检查是否登录
        :param request:
        :return:
        """
        if request.session.get('admin') is None:
            return JsonResponse({
                'status': False,
                'errMsg': '你还未登录'
            }, status=401)
        admin_user = getAdminUser(email=request.session.get('admin'))
        return JsonResponse({
            'status': True,
            'id': admin_user.id,
            'email': admin_user.email
        })

    def post(self, request):
        """
        登录管理员账户
        :param request:
        :return:
        """
        try:
            jsonParams = json.loads((request.body).decode('utf-8'))
            admin_user = AdminAccount.objects.filter(email=jsonParams.get('email', ''))
            if not admin_user.exists():
                return JsonResponse({
                    'status': False,
                    'errMsg': '管理员账户不存在'
                }, status=404)
            admin_user = admin_user[0]
            db_password = admin_user.password.password
            if check_password(jsonParams.get('password', ''), db_password):
                request.session['admin'] = admin_user.email
                admin_user.last_login_time = now
                return JsonResponse({
                    'status': True,
                    'id': admin_user.id,
                    'email': admin_user.email,
                    'username': admin_user.username
                })
            else:
                return JsonResponse({
                    'status': False,
                    'errMsg': '密码错误'
                }, status=401)
        except Exception as ex:
            return JsonResponse({
                'status': False,
                'errMsg': str(ex)
            })

    @check_admin_login
    def delete(self, request):
        """
        登出管理员账户
        :param request:
        :return:
        """
        admin_user = getAdminUser(request.session.get('admin'))
        request.session['admin'] = None
        return JsonResponse({
            'status': True,
            'id': admin_user.id
        })
